<template>
  <div class='number-grow-warp flex'>
    <span ref="numberGrow" class="number-grow" :class="type" :data-time="time" :data-value="value" :style="fontStyle">0</span>
    <span class="unit" v-if="unit">{{ unit }} </span>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 0
    },
    time: {
      type: Number,
      default: 2
    },
    unit: {
      type: String,
    },
    fontStyle: {
      type: Object,
      default: () => ({fontFamily: 'Oswald'})
    },
    type: {
      type: String,
      default: 'normal'
    }
  },
  data () {
    return {

    };
  },
  mounted () {
    this.numberGrow(this.$refs.numberGrow)
  },
  computed: {},
  watch: {
    value: {
      handler () {
        this.numberGrow(this.$refs.numberGrow)
      },
      deep: true
    }
  },
  methods: {
    // 文字变化效果
    numberGrow (ele) {
      // debugger;
      let step = parseInt((this.value * 100) / (this.time * 1000));
      let current = 0
      let start = 0
      let t = setInterval(() => {
        start += step
        if (start > this.value) {
          clearInterval(t)
          start = this.value
          t = null
        }
        if (start == 0) {
          const current = 0
          ele.innerHTML = current.toString()
          start = this.value;
          clearInterval(t)
        }
        // 当前值等于开始值，那就结束
        if (this.value === 0) {
          return
        }
        current = start
        ele.innerHTML = current.toString().replace(/(\d)(?=(?:\d{3}[+]?)+$)/g, '$1,')
      }, this.time * 100)
    }
  }
}
</script>

<style lang='less' scoped>
.number-grow-warp {
  transform: translateZ(0);
}
.number-grow {
  display: block;
  margin-right: 12px;
  transition: transform 1s ease-in-out;
  box-sizing: border-box;
}
.unit {
  display: inline-block;
  font-family: Source Han Sans CN;
  font-weight: 400;
  font-size: 14px;
  line-height: 35px;
  color: #d9e7ff;
  vertical-align: bottom;
}
.large {
  font-family: Oswald;
  font-weight: 500;
  font-size: 40px;
  color: #ffffff;
}
.normal {
  font-family: Oswald;
  font-weight: 500;
  font-size: 20px;
  color: #30dcff;
}
</style>